<template>
  <div class="common-layout">
    <el-form class="header" :model="queryParam" ref="queryRef" :inline="true">
      <el-form-item label="名称" prop="name">
        <el-input
            style="width: 200px"
            v-model="queryParam.name"
            placeholder="请输入任务名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="校区" prop="name">
        <el-tree-select
            style="width: 200px"
            v-model="queryParam.dept"
            :data="enabledDeptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="选择校区"
            check-strictly />
      </el-form-item>

      <el-form-item label="状态" prop="active">
        <el-select v-model="queryParam.active" placeholder="请选择任务状态" clearable style="width: 200px">
          <el-option
              v-for="dict in task_active_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
<!--        <el-button icon="Refresh" >{{message}}</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-left: 15px;margin-bottom: 10px">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="handleAdd"
        >新增(通用)
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            @click="handleWord"
        >新增(单词)
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            :disabled="single"
            @click="handleCopyAll"
        >复制
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :sm="24" :lg="24" style="padding-left: 20px">
        <el-table :data="stepList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="编号" width="60" align="center" prop="id"/>
          <el-table-column label="名称" align="center" prop="name"/>
          <el-table-column label="校区"  width="80" align="center" prop="campus"/>

          <el-table-column label="已分配的学生" min-width="200" align="center" prop="studentName">
          </el-table-column>

          <el-table-column label="时间范围" width="320" align="center" prop="scope"/>
          <el-table-column v-if="false" label="创建时间" align="center" prop="time">
            <template #default="scope">
              <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column width="80" label="总步数" align="center" prop="total"/>

          <el-table-column width="80" label="状态" align="center" prop="active">
            <template #default="scope">
              <dict-tag :options="task_active_status" :value="scope.row.active"/>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template #default="scope">
              <div>
                <el-button
                    link
                    v-if="scope.row.active !== 1"
                    type="warning"
                    @click="handleAddStep(scope.row)"
                >添加步骤
                </el-button>
                <el-button
                    type="text"
                    @click="handleShowStep(scope.row.id)"
                >查看步骤
                </el-button>
                <el-button
                    v-if="scope.row.active === 3"
                    link
                    type="success"
                    @click="handleAddStudent(scope.row)"
                >分配学生
                </el-button>
                <el-button
                    link
                    v-if="scope.row.active === 3 && scope.row.studentName !== null"
                    style="color: #421f7d"
                    @click="startTask(scope.row)"
                >开始任务
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            style="margin-right: 20px"
            v-show="size > 0"
            :total="size"
            v-model:page="queryParam.pageNum"
            v-model:limit="queryParam.pageSize"
            @pagination="handleQuery"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改主任务   -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="dictRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-form-item v-if="false" label="总步数" prop="total">
          <el-input-number style="width: 100%" v-model="form.total" placeholder="请输入总步数"/>
        </el-form-item>
        <el-form-item label="时间范围" prop="scope">
          <el-date-picker
              v-model="form.scopeTemp"
              type="daterange"
              @change="dateChange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="default"
          />
        </el-form-item>
        <el-form-item label="校区" prop="campus">
          <el-tree-select
              style="width: 100%"
              @change="selectChange"
              v-model="form.campus"
              :data="enabledDeptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
              placeholder="校区" check-strictly />
        </el-form-item>

        <el-form-item v-if="open_word" label="书名" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form.book" placeholder="请选择书名(可不选,添加步骤中需要)">
            <el-option v-for="item in 7" :key="item" :label="`${('book')}${item}`" :value="`${('book')}${item}`"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="open_word" label="单元" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form.unit" placeholder="请选择单元(可不选,添加步骤中需要)">
            <el-option v-for="item in 6" :key="item" :label="`${('unit')}${item}`" :value="`${('unit')}${item}`"/>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改步骤(通用+单词) -->
    <el-dialog :title="titleDetail" v-model="openDetail" width="700px" append-to-body>
      <el-form ref="formDetail" :model="form2" :rules="rules" label-width="80px">

        <el-form-item label="步骤" width="60" prop="step">
          <el-input-number style="width: 100%" v-model="form2.step" placeholder="请输入步骤(1,2,3...)"/>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="form2.title" placeholder="请输入标题"/>
        </el-form-item>

        <el-form-item v-if="!openDetail_word" label="内容" prop="content">
          <el-input v-model="form2.content" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="限时" prop="time">
          <el-date-picker
              @change="dateDetailChange"
              style="width: 100%"
              v-model="form2.time"
              type="datetime"
              placeholder="请选择截止时间"
          />
        </el-form-item>

        <el-form-item v-if="openDetail_word" label="书名" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form2.book" placeholder="请选择书名">
            <el-option v-for="item in 7" :key="item" :label="`${('book')}${item}`" :value="`${('book')}${item}`"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="openDetail_word" label="单元" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form2.unit" placeholder="请选择单元">
            <el-option v-for="item in 6" :key="item" :label="`${('unit')}${item}`" :value="`${('unit')}${item}`"/>
          </el-select>
        </el-form-item>

        <el-form-item v-if="openDetail_word" label="类型" prop="ipaddr">
          <el-select style="width: 100%" clearable v-model="form2.type" placeholder="请选择类型">
            <el-option v-for="item in typeStatus" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFormDetail">确 定</el-button>
          <el-button @click="cancelDetail">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="查看步骤" v-model="showDetail" width="1000px" append-to-body custom-class="my-dialog">
      <el-steps v-if="false" style="margin: 10px 0" :active="active" finish-status="success">
        <el-step title="Step 1"/>
        <el-step title="Step 2"/>
        <el-step title="Step 3"/>
      </el-steps>
      <el-table border :data="task_detailList">
        <el-table-column label="步骤" width="60" align="center" prop="step"/>
        <el-table-column label="标题" align="center" prop="title"/>
        <el-table-column label="内容" min-width="300" align="center" prop="content"/>
        <el-table-column label="截止时间" width="240" align="center" prop="time"/>
        <el-table-column v-if="false" label="学生" align="center" prop="student"/>
        <el-table-column v-if="false" label="校区" width="70" align="center" prop="campus"/>
        <el-table-column v-if="false" label="状态" align="center" prop="status"/>
        <el-table-column v-if="false" label="总步数" width="70" align="center" prop="total"/>
        <el-table-column v-if="false" label="状态" width="90" align="center" prop="active">
          <template #default="scope">
            <dict-tag :options="task_active_status" :value="scope.row.active"/>
          </template>
        </el-table-column>
        <el-table-column label="修改" align="center" width="80" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
                v-if="scope.row.active === 3"
                link
                type="danger"
                @click="updateDetail(scope.row)"
            >修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="添加学生" v-model="addStudent" width="500px" height="500px" append-to-body>
      <el-form ref="formDetail" :model="form3" label-width="100px">
        <el-form-item v-if="false" label="学生" prop="student">
          <el-input v-model="form3.student" placeholder="请输入学生"/>
        </el-form-item>

        <el-form-item  label="已分配:" prop="studentName">
          <el-link style="margin: 0 10px" @click="studentUpdate(item)" v-for="(item,index) in form3.already"
                   :key="index">{{ item }}
          </el-link>
        </el-form-item>

        <el-form-item v-if="false"  label="已分配:" prop="studentList">
          <el-link style="margin: 0 10px" @click="studentUpdate(item)" v-for="(item,index) in form3.already"
                   :key="index">{{ item.toString().substring(0,item.toString().indexOf('-')) }}
          </el-link>
        </el-form-item>

        <el-form-item label="学生" prop="student">
          <el-select placeholder="学生选择" filterable clearable style="width: 100%" v-model="form3.studentId">
            <el-option
                v-for="item in studentsList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addStudent = false">取消</el-button>
          <el-button type="primary" @click="addStudentSubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref} from "vue";
import {
  addStep, addStep_progress,
  addTask_detail,
  updateTask_detail,
  addTaskAddstudent,
  delStep,
  delTaskAddstudent,
  getStep,
  listStep,
  listTask_detail, listTaskAddstudent,
  updateStep,
  updateTask_start, typeStatus
} from "@/api/teach/step.js";
import {parseTime} from "@/utils/ruoyi.js";
import {getUserList} from "@/api/system/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {deptTreeSelect} from "@/api/system/user"

const {proxy} = getCurrentInstance()

let queryParam = ref({
  pageNum: 1,
  pageSize: 10
})
let queryDetails = ref({
  main: undefined
})

const ids = ref([])
const single = ref(true)
const multiple = ref(true)
let size = ref(0)
const {task_active_status} = proxy.useDict("task_active_status")
const enabledDeptOptions = ref(undefined)
const active = ref(0)
let stepList = ref([])
let studentsList = ref([])
let task_detailList = ref([])
let title = ref('')
let titleDetail = ref('')
let form = ref({})
let form2 = ref({})
let form3 = ref({})
let rowRecord = ref({})
let formDetail = ref({})
let addStudentFrom = ref({})
let open = ref(false)
let open_word = ref(false)
let addStudent = ref(false)
let openDetail = ref(false)
let openDetail_word = ref(false)
let showDetail = ref(false)
let showSteps = ref(false)
let rules = ref({})

initPage()

function initPage() {
  handleQuery()
  getDeptTree()
}

// 组件挂载时注册事件监听
onMounted(() => {
  // 监听事件（回调可以是 async 函数）
  // eventBus.on('user_complete', handleUserUpdate);
  // eventBus.on('complete', handleEvent);
  // console.log("---")
});

onUnmounted(() => {
  // console.log("+++")
  // 移除监听，避免内存泄漏
  // eventBus.off('user_complete', handleUserUpdate);
});

//查询学生列表
function getUserListByDept(dept){
  getUserList(200, dept).then(res => {
    studentsList.value = res.data
    // console.log(res)
  })
}

function updateDetail(row){
  titleDetail.value = '修改步骤'
  openDetail.value = true
  // console.log(row)
  form2.value = row
}

//时间事件-主
function dateChange(date) {
  let parseTime1 = parseTime(date[0],'{y}-{m}-{d} {h}:{i}:{s}');
  let parseTime2 = parseTime(date[1],'{y}-{m}-{d} {h}:{i}:{s}');
  form.value.scope = parseTime1 + ' 至 ' + parseTime2
}

//时间事件-详情
function dateDetailChange(date) {
  form2.value.time = parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}')
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

//校区改变事件
function selectChange(val) {
  form.value.dept = val
  form.value.campus = findLabelById(enabledDeptOptions.value, val);
}

/**
 * 通过ID 查找 el-tree-select中data的label
 * */
function findLabelById(data, id) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id === id) {
      return data[i].label;
    }
    if (data[i].children && data[i].children.length > 0) {
      const result = findLabelById(data[i].children, id);
      if (result) return result;
    }
  }
  return null; // 如果没有找到对应id的label，则返回null
}

/**
 * 添加学生数据提交
 * */
function addStudentSubmit() {
  let number = studentsList.value.findIndex(item => {
    return item.userId === form3.value.studentId
  });
  let name = studentsList.value[number]['userName'];
  // console.log(name)
  // console.log(rowRecord.value.studentName)
  if (rowRecord.value.studentName != null && rowRecord.value.studentName.indexOf(name) !== -1) {
    proxy.$modal.msgWarning("已经存在学生:" + name);
    form3.value.studentId = []
    return
  }
  addStudentFrom.value = {}
  addStudent.value = false
  addStudentFrom.value.studentId = form3.value.studentId
  addStudentFrom.value.studentName = name
  addStudentFrom.value.main = rowRecord.value.id
  addStudentFrom.value.campus = rowRecord.value.campus
  addStudentFrom.value.scope = rowRecord.value.scope
  addStudentFrom.value.name = rowRecord.value.name
  addStudentFrom.value.total = rowRecord.value.total

  addTaskAddstudent(addStudentFrom.value).then(res => {
    if (res.code === 200) {
      // console.log(res)
      proxy.$modal.msgSuccess("学生新增成功");
      addStudent.value = false
      handleQuery()
    }
  })
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    // deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

function submitForm() {
  if (form.value.id !== undefined) {
    updateStep(form.value).then(response => {
      proxy.$modal.msgSuccess("任务修改成功");
      handleQuery()
    })
  }
  else {
    addStep(form.value).then(response => {
      proxy.$modal.msgSuccess("新增任务成功");
      handleQuery()
    });
  }
  open.value = false
  open_word.value = false
}

function handleCopyAll(){
  const id = ids.value
  proxy.$modal.confirm('是否确认复制编号为:' + id + '的任务？').then(function (){
    return handleCopy()
  }).then(() => {
    handleQuery()
    proxy.$modal.msgSuccess("复制成功")
  }).catch(() => {
    proxy.$modal.msg("取消复制")
  })
}

function handleDelete(row){
  const id = row.id || ids.value
  proxy.$modal.confirm('是否确认删除"' + id + '"的数据项？').then(function() {
    return delStep(id)
  }).then(() => {
    handleQuery()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
    proxy.$modal.msg("取消删除")
  })
}

function cancel() {
  open.value = false;
  open_word.value = false;
  proxy.$modal.msg("取消操作");
}

function cancelDetail() {
  openDetail.value = false;
  openDetail_word.value = false;
  proxy.$modal.msg("取消操作");
}

function submitFormDetail() {
  if (openDetail_word.value){
    form2.value.content = "需要完成的单词学习:书名-'" + form2.value.book + "',单元-'" + form2.value.unit + "'"
  }
  if (form2.value.id === undefined) {
    addTask_detail(form2.value).then(response => {
      // console.log(response)
      if (response.code === 200) {
        proxy.$modal.msgSuccess("添加成功")
        openDetail.value = false;
        openDetail_word.value = false;
        handleQuery()
      }
    })
  } else {
    updateTask_detail(form2.value).then(response => {
      // console.log(response)
      if (response.code === 200) {
        proxy.$modal.msgSuccess("修改成功")
        openDetail.value = false;
        openDetail_word.value = false;
      }
    })
  }
}

function startTask(row){
  let id = row.id
  let mainFrom = {
    active: 2,
    id: id
  }
  startTaskNewTable(row)
  updateStep(mainFrom).then(response => {
    // console.log(response)
    if (response.code === 200) {
      let formDetail = {
        main: id,
        step: 1,
        active: 3
      }
      updateTask_start(formDetail).then(response => {
        // console.log(response)
        if (response.code === 200) {
          proxy.$modal.msgSuccess("任务开始");
          handleQuery()
        }
      })
    }
  })
}

function startTaskNewTable(row){
  // console.log(row)
  let tableForm = {
    main: row.id,
    total: row.total,
    name: row.name,
    scope: row.scope,
    rate: row.rate,
    step: 1,
    active: 3
  }
  let childForm = {
    main: row.id,
    step: 1,
  }
  listTask_detail(childForm).then(response => {
    if (response.code === 200) {
      // console.log(response)
      tableForm.title = response.rows[0].title
      tableForm.content = response.rows[0].content
      tableForm.end = response.rows[0].time
      tableForm.type = response.rows[0].type
      listTaskAddstudent(childForm).then(response => {
        if (response.code === 200) {
          // console.log(response)
          let studentData = response.rows
          studentData.forEach(item => {
            tableForm.studentId = item.studentId
            tableForm.studentName = item.studentName
            addStep_progress(tableForm)
          })
        }
      })
    }
  })
}

function resetQuery() {
  queryParam.value = {}
  initPage()
}

//添加主任务-1
function handleAdd() {
  open.value = true
  open_word.value = false
  title.value = "添加任务"
  form.value.type = 1
}

//添加主任务-2
function handleWord() {
  open.value = true
  open_word.value = true
  form.value.type = 2
  title.value = "添加单词任务"
}

function handleQuery() {
  // console.log(queryParam)
  listStep(queryParam.value).then(response => {
    // console.log(response)
    size.value = response.total
    stepList.value = response.rows;
  });
}

function getStudentNameOnly(item){
  // console.log(item.studentList)
  let students = item.toString().split(',');
  // console.log(students);
  let list = []
  for (let i = 0; i < students.length; i++) {
    list.push(students[i].substring(0,students[i].indexOf("-")));
  }
  return list.join(",");
}

function handleUpdate(row) {
  const id = row.id || ids.value
  getStep(id).then(response => {
    // console.log(response)
    form.value = response.data
    open.value = true
  })
}

function handleCopy() {
  const id = ids.value
  let form = {}
  getStep(id).then(response => {
    if (response.code === 200) {
      form = response.data
      // console.log(form)
      form.id = null
      form.studentId = null
      form.studentName = null
      form.active = 3
      form.send = 0
      addStep(form).then(response => {
        if (response.code === 200) {
          // console.log(response)
          let main = response.data
          queryDetails.value.main = id[0]
          listTask_detail(queryDetails.value).then(response => {
            // console.log(response)
            if (response.code === 200) {
              let details = response.rows
              details.forEach(item => {
                item.id = null
                item.main = main
                addTask_detail(item)
              })
            }
            handleQuery()
          });
        }
      })
    }
  })
}

function studentUpdate(row) {
  // console.log(row)
  ElMessageBox({
    title: '删除提示',
    message: h('p', null, [
      h('span', null, '确定移除“' + row.toString().substring(0,row.toString().indexOf('-')) + '”吗?'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '正在移除',
    })
    let id = row.toString().split('-')[1];
    // console.log(id)
    delTaskAddstudent(id).then(res => {
      if (res.code === 200) {
        addStudent.value = false
        handleQuery()
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消操作',
    })
  })
}

/**
 * 添加学生
 * */
function handleAddStudent(row) {
  // console.log(row)
  form3.value.studentId = [];
  addStudent.value = true
  rowRecord.value = row
  // form3.value.already = row.studentList.toString().split(",")
  if (row.studentName !== null && row.studentName !== undefined) {
    form3.value.already = row.studentName.toString().split(",")
  }
  else {
    form3.value.already = ''
  }
  // console.log(form3.value.already)
  getUserListByDept(row.dept)
}

/**
 * 图示
 * */
function pictureDetail(row) {
  active.value = row.active
  showSteps.value = true;
}

/**
 * 添加步骤
 * */
function handleAddStep(row) {
  // console.log(form.value)
  openDetail.value = true;
  openDetail_word.value = row.type === '2';
  titleDetail.value = "添加步骤-(" + row.name + ")"
  form2.value.main = row.id
  form2.value.name = row.name
  form2.value.total = row.total
  form2.value.campus = row.campus
  form2.value.type = parseInt(row.type)
  //提前赋值
  form2.value.book = form.value.book || row.book
  form2.value.unit = form.value.unit || row.unit
}

/**
 * 查看步骤
 * */
function handleShowStep(id) {
  // console.log(id)
  showDetail.value = true;
  queryDetails.value.main = id;
  // console.log(queryDetails.value);
  listTask_detail(queryDetails.value).then(response => {
    // console.log(response)
    task_detailList.value = response.rows;
  });
}
</script>

<style scoped lang="scss">
.header {
  margin-top: 20px;
  margin-left: 20px;
}

.my-dialog {
  position: absolute;
  top: 10%; /* 根据实际情况调整 */
  left: 50%;
  transform: translateX(-50%);
}

.button-container {
  display: flex;
  justify-content: space-around; /* 按钮均匀分布 */
  /* 或者使用 'space-between' 让第一个按钮靠左，最后一个按钮靠右 */
}
</style>
